import {config} from "../config/config";
import {promisic} from "./util";
import {Token} from "../model/token"
import {codes} from "../config/exception-config"

class Http {
    static async request({url, data, method = 'GET'}) {
        let res
        try {
            res = await promisic(wx.request)({
                url: `${config.apiBaseUrl}${url}`,
                data,
                method,
                header: {
                    'content-type':'application/json',
                    'Authorization': `Bearer ${wx.getStorageSync('token')}`
                }
            })
        }
        catch(e) {
            Http.showError(-1)
        }
        if (!res) {
            return null
        }
        const code = res.statusCode.toString()
        if (code.startsWith('2')) {
            return res.data
        }else {
            if (code === '401') {
                wx.removeStorageSync('user')
                wx.removeStorageSync('token')
                const token = new Token()
                await token.verify()
            }else if (code === '404') {
                wx.removeStorageSync('user')
                wx.removeStorageSync('token')
                const token = new Token()
                await token.verify()
            } else {
                wx.showToast({
                    icon: "none",
                    title: res.data.error,
                    duration: 3000
                })
            }
        }
    }

    static async _refetch(data) {
        const token = new Token()
        await token.getTokenFromServer()
        data.refetch = false
        return await Http.request(data)
    }

    static showError(error_code, serverError) {
        let tip
        if (!error_code) {
            tip = codes[9999]
        }else {
            if (codes[error_code] === undefined) {
                tip = serverError.message
            }else {
                tip = codes[error_code]
            }
        }
        wx.showToast({
            icon: "none",
            title: tip,
            duration: 3000
        })
    }
}
export {
    Http
}
